﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace xmlTranslate
{
    public class YouDaoTranslate : ITranslate
    {
        public string Translate(string sourceStr, bool saveSource = true)
        {
            sourceStr = sourceStr.Replace("\r", "").Replace("\n", "").Trim();
            HttpHelper httpHelper = new HttpHelper();
            var request = httpHelper.GetHtml(new HttpItem
            {
                URL = "http://fanyi.youdao.com/translate?&doctype=json&type=EN2ZH_CN&i=" + sourceStr
            });



            try
            {
                var res = JsonConvert.DeserializeObject<Res1>(request.Html);
                string str = res.translateResult.SelectMany(p => p).Where(p => !string.IsNullOrWhiteSpace(p.tgt)).Select(p => p.tgt).Distinct().FirstOrDefault();
                if (str != null)
                {
                    if (saveSource)
                        return $"{str}({sourceStr})";
                }
                return sourceStr;
            }
            catch
            {
                return sourceStr;
            }
        }

    }


    public class Res1
    {
        public string type { get; set; }
        public string errorCode { get; set; }
        public string elapsedTime { get; set; }

        public List<List<Result>> translateResult { get; set; }
    }
    public class Result
    {
        public string src { get; set; }
        public string tgt { get; set; }

    }
}
